package czk.concrent.enjoyModelWithNotLock.atomicInterger.practice;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntUnaryOperator;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/12/16 22:13
 */
public class UpdateAndGet {
    public static void main(String[] args) {
        UpdateAndGet updateAndGet=new UpdateAndGet();
        AtomicInteger atomicInteger=new AtomicInteger(1);
        AtomicInteger update = updateAndGet.update(atomicInteger, i -> i * 10);
        System.out.println(update.get());
    }

    /**
     * 原子更新
     * @param atomicInteger
     * @param intUnaryOperator
     * @return
     */
    public AtomicInteger update(AtomicInteger atomicInteger, IntUnaryOperator intUnaryOperator){
        while (true){
            // 拿到原始值
            int i = atomicInteger.get();
            // 操作值
            int i1 = intUnaryOperator.applyAsInt(i);
            if (atomicInteger.compareAndSet(i,i1)){
                return atomicInteger;
            }
        }
    }
}
